<?php

namespace App\Kuafu\Robot\Service;

use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Robot\Enum\RmsRobotCodeEnum;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Redis;

class RmsBotSendService extends BaseService
{
    private array  $msgData;
    private string $msgType = 'interactive';

    public function getRobot()
    {
        if ('prod' == config('app.env')) {
            return [
                'appId'     => 'cli_a12887c737b8900d',
                'appSecret' => 'xXRyhS9jb1EisEvG4jwrCbcUHXOv1mmJ'
            ];
        } elseif ('pre' == config('app.env')) {
            return [
                'appId'     => 'cli_a263be1762b8d00d',
                'appSecret' => 'nlfoaBAAax8ESgOnTzGsKaZ6WKXtzrUg'
            ];
        } else {
            return [
                'appId'     => 'cli_a12887c737b8900d',
                'appSecret' => 'xXRyhS9jb1EisEvG4jwrCbcUHXOv1mmJ'
            ];
        }
    }

    /**
     * 获取token
     */
    public function getTenantAccToken($appid, $appSecret)
    {
        $tenantToken = Redis::get('RMS_ROBOT:' . $appid);
        if (!$tenantToken) {
            $client      = new GuzzleClient();
            $body        = ['app_id' => $appid, 'app_secret' => $appSecret];
            $body        = json_encode($body);
            $url         = 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal';
            $response    = $client->request("POST", $url, ['body' => $body, 'timeout' => 10]);
            $response    = $response->getBody()->getContents();
            $responseArr = json_decode($response, true);
            Redis::setex('RMS_ROBOT' . $appid, $responseArr['expire'],
                $responseArr['tenant_access_token']);
            return $responseArr['tenant_access_token'];
        } else {
            return $tenantToken;
        }
    }


    /**
     * 主动批量发送消息
     */
    public function batchSendMessage()
    {
        // TODO 调用飞书批量发送接口
        return;
    }

    /**
     * 主动发型消息
     *
     * @param string $receiveId
     * @param string $receiveType open_id/user_id/union_id/email/chat_id
     * @return array|mixed
     * @throws GuzzleException
     */
    public function sendMessage(
        string $receiveId,
        string $receiveType = 'user_id'
    ) {
        if (!$receiveId) {
            return [];
        }
        $url    = 'https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=' . $receiveType;
        $client = new GuzzleClient();
        $body   = [
            'receive_id' => $receiveId,
            'content'    => json_encode($this->msgData),
            'msg_type'   => $this->msgType
        ];

        $body     = json_encode($body);
        $response = $client->request('POST', $url, [
            'body'        => $body,
            'headers'     => [
                'Content-Type'  => "application/json; charset=utf-8",
                'Authorization' => self::getAccToken()
            ],
            'timeout'     => 10,
            'http_errors' => false,
        ]);
        $response = $response->getBody()->getContents();

        return json_decode($response, true);
    }

    /**
     * 回复消息
     *
     * @param string $messageId
     * @return mixed
     * @throws GuzzleException
     */
    public function replyMessage(
        string $messageId
    ) {
        $url    = 'https://open.feishu.cn/open-apis/im/v1/messages/' . $messageId . '/reply';
        $client = new GuzzleClient();
        $body   = [
            'content'  => json_encode($this->msgData),
            'msg_type' => $this->msgType
        ];

        $body     = json_encode($body);
        $response = $client->request('POST', $url, [
            'body'        => $body,
            'headers'     => [
                'Content-Type'  => "application/json; charset=utf-8",
                'Authorization' => self::getAccToken()
            ],
            'timeout'     => 10,
            'http_errors' => false,
        ]);
        $response = $response->getBody()->getContents();
        return json_decode($response, true);
    }

    public function getAccToken()
    {
        $robot    = self::getRobot();
        $accToken = 'Bearer ' . self::getTenantAccToken($robot['appId'], $robot['appSecret']);
        return $accToken;
    }


    /**
     * 设置通用 content 消息体
     *
     * @param string $msg
     * @return array
     */
    public function setGeneralMsg(string $msg = ''): array
    {
        $this->msgData = [
            'config'   => [
                "wide_screen_mode" => true
            ],
            'elements' => [
                ['tag' => 'markdown', 'content' => $msg]
            ]
        ];
        return $this->msgData;
    }

}
